package com.ikingtech.framework.sdk.authenticate.operation;

import com.ikingtech.framework.sdk.cache.constants.CacheConstants;
import com.ikingtech.framework.sdk.enums.authenticate.SignEndpointTypeEnum;
import com.ikingtech.framework.sdk.utils.Tools;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.*;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class IdentityOps {

    private final StringRedisTemplate redisTemplate;

    /**
     * 踢人下线
     *
     * @param identityId userId
     */
    public void offline(String identityId) {
        List<String> allTokens = new ArrayList<>();
        List<String> allEndpoints = new ArrayList<>();
        for (SignEndpointTypeEnum value : SignEndpointTypeEnum.values()) {
            List<String> tokens = this.redisTemplate.opsForList().range(CacheConstants.loginUserFormat(identityId, value.name()), 0, -1);
            if (Tools.Coll.isNotBlank(tokens)) {
                allTokens.addAll(tokens);
            }
            allEndpoints.add(CacheConstants.loginUserFormat(identityId, value.name()));
        }
        this.redisTemplate.delete(allEndpoints);
        this.redisTemplate.delete(allTokens);
    }

    /**
     * 踢人下线,指定了终端类型
     *
     * @param identityId userId
     * @param endpoint   终端类型
     */
    public void offline(String identityId, SignEndpointTypeEnum endpoint) {
        List<String> tokens = this.redisTemplate.opsForList().range(CacheConstants.loginUserFormat(identityId, endpoint.name()), 0, -1);
        this.redisTemplate.delete(CacheConstants.loginUserFormat(identityId, endpoint.name()));
        this.redisTemplate.delete(Optional.ofNullable(tokens).orElse(new ArrayList<>()));
    }
}
